<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/midium.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/small.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="实用工具,正则表达式," />




  


  <link rel="alternate" href="/atom.xml" title="磊迹" type="application/atom+xml" />






<meta name="description" content="一些实用工具">
<meta property="og:type" content="article">
<meta property="og:title" content="实用工具——正则表达式">
<meta property="og:url" content="http://yoursite.com/%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/index.html">
<meta property="og:site_name" content="磊迹">
<meta property="og:description" content="一些实用工具">
<meta property="og:image" content="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/600e9c75-5033-4dad-ae2b-930957db638e.png">
<meta property="article:published_time" content="2019-05-31T16:00:00.000Z">
<meta property="article:modified_time" content="2023-08-20T07:59:22.334Z">
<meta property="article:author" content="Lei Zhou">
<meta property="article:tag" content="实用工具">
<meta property="article:tag" content="正则表达式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/600e9c75-5033-4dad-ae2b-930957db638e.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/常用工具/正则表达式/"/>





  <title>实用工具——正则表达式 | 磊迹</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/zlleige" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">磊迹</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">热爱可抵岁月漫长</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Lei Zhou">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/title.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="磊迹">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">实用工具——正则表达式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-06-01T00:00:00+08:00">
                2019-06-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E5%AE%9E%E7%94%A8%E5%B7%A5%E5%85%B7/" itemprop="url" rel="index">
                    <span itemprop="name">实用工具</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          
              <div class="post-description">
                  一些实用工具
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <!-- GFM-TOC -->

<ul>
<li><a href="#一概述">一、概述</a></li>
<li><a href="#二匹配单个字符">二、匹配单个字符</a></li>
<li><a href="#三匹配一组字符">三、匹配一组字符</a></li>
<li><a href="#四使用元字符">四、使用元字符</a></li>
<li><a href="#五重复匹配">五、重复匹配</a></li>
<li><a href="#六位置匹配">六、位置匹配</a></li>
<li><a href="#七使用子表达式">七、使用子表达式</a></li>
<li><a href="#八回溯引用">八、回溯引用</a></li>
<li><a href="#九前后查找">九、前后查找</a></li>
<li><a href="#十嵌入条件">十、嵌入条件</a></li>
<li><a href="#参考资料">参考资料</a><!-- GFM-TOC -->


</li>
</ul>
<h1 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h1><p>正则表达式用于文本内容的查找和替换。</p>
<p>正则表达式内置于其它语言或者软件产品中，它本身不是一种语言或者软件。</p>
<p><a href="https://regexr.com/" target="_blank" rel="noopener">正则表达式在线工具</a></p>
<h1 id="二、匹配单个字符"><a href="#二、匹配单个字符" class="headerlink" title="二、匹配单个字符"></a>二、匹配单个字符</h1><p><strong>.</strong>   可以用来匹配任何的单个字符，但是在绝大多数实现里面，不能匹配换行符；</p>
<p><strong>.</strong>   是元字符，表示它有特殊的含义，而不是字符本身的含义。如果需要匹配 . ，那么要用 \ 进行转义，即在 . 前面加上 \ 。</p>
<p>正则表达式一般是区分大小写的，但也有些实现不区分。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">C</span><span class="selector-class">.C2018</span></span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<p>My name is   <strong>CyC2018</strong>  .</p>
<h1 id="三、匹配一组字符"><a href="#三、匹配一组字符" class="headerlink" title="三、匹配一组字符"></a>三、匹配一组字符</h1><p><strong>[ ]</strong>   定义一个字符集合；</p>
<p>0-9、a-z 定义了一个字符区间，区间使用 ASCII 码来确定，字符区间在 [ ] 中使用。</p>
<p><strong>-</strong>   只有在 [ ] 之间才是元字符，在 [ ] 之外就是一个普通字符；</p>
<p><strong>^</strong>   在 [ ] 中是取非操作。</p>
<p><strong>应用</strong>  </p>
<p>匹配以 abc 为开头，并且最后一个字母不为数字的字符串：</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">abc[^<span class="number">0</span><span class="number">-9</span>]</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<ol>
<li><strong>abcd</strong>  </li>
<li>abc1</li>
<li>abc2</li>
</ol>
<h1 id="四、使用元字符"><a href="#四、使用元字符" class="headerlink" title="四、使用元字符"></a>四、使用元字符</h1><h2 id="匹配空白字符"><a href="#匹配空白字符" class="headerlink" title="匹配空白字符"></a>匹配空白字符</h2><table>
<thead>
<tr>
<th align="center">元字符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">[\b]</td>
<td align="center">回退（删除）一个字符</td>
</tr>
<tr>
<td align="center">\f</td>
<td align="center">换页符</td>
</tr>
<tr>
<td align="center">\n</td>
<td align="center">换行符</td>
</tr>
<tr>
<td align="center">\r</td>
<td align="center">回车符</td>
</tr>
<tr>
<td align="center">\t</td>
<td align="center">制表符</td>
</tr>
<tr>
<td align="center">\v</td>
<td align="center">垂直制表符</td>
</tr>
</tbody></table>
<p>\r\n 是 Windows 中的文本行结束标签，在 Unix/Linux 则是 \n。</p>
<p>\r\n\r\n 可以匹配 Windows 下的空白行，因为它匹配两个连续的行尾标签，而这正是两条记录之间的空白行；</p>
<h2 id="匹配特定的字符"><a href="#匹配特定的字符" class="headerlink" title="匹配特定的字符"></a>匹配特定的字符</h2><h3 id="1-数字元字符"><a href="#1-数字元字符" class="headerlink" title="1. 数字元字符"></a>1. 数字元字符</h3><table>
<thead>
<tr>
<th align="center">元字符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">\d</td>
<td align="center">数字字符，等价于 [0-9]</td>
</tr>
<tr>
<td align="center">\D</td>
<td align="center">非数字字符，等价于 [^0-9]</td>
</tr>
</tbody></table>
<h3 id="2-字母数字元字符"><a href="#2-字母数字元字符" class="headerlink" title="2. 字母数字元字符"></a>2. 字母数字元字符</h3><table>
<thead>
<tr>
<th align="center">元字符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">\w</td>
<td align="center">大小写字母，下划线和数字，等价于 [a-zA-Z0-9_]</td>
</tr>
<tr>
<td align="center">\W</td>
<td align="center">对 \w 取非</td>
</tr>
</tbody></table>
<h3 id="3-空白字符元字符"><a href="#3-空白字符元字符" class="headerlink" title="3. 空白字符元字符"></a>3. 空白字符元字符</h3><table>
<thead>
<tr>
<th align="center">元字符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">\s</td>
<td align="center">任何一个空白字符，等价于 [\f\n\r\t\v]</td>
</tr>
<tr>
<td align="center">\S</td>
<td align="center">对 \s 取非</td>
</tr>
</tbody></table>
<p>\x 匹配十六进制字符，\0 匹配八进制，例如 \xA 对应值为 10 的 ASCII 字符 ，即 \n。</p>
<h1 id="五、重复匹配"><a href="#五、重复匹配" class="headerlink" title="五、重复匹配"></a>五、重复匹配</h1><ul>
<li><strong>+</strong>   匹配 1 个或者多个字符</li>
<li><strong>\</strong>  * 匹配 0 个或者多个字符</li>
<li><strong>?</strong>   匹配 0 个或者 1 个字符</li>
</ul>
<p><strong>应用</strong>  </p>
<p>匹配邮箱地址。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight taggerscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="symbol">\w</span>.]+@<span class="symbol">\w</span>+<span class="symbol">\.</span><span class="symbol">\w</span>+</span><br></pre></td></tr></table></figure>

<p>[\w.] 匹配的是字母数字或者 . ，在其后面加上 + ，表示匹配多次。在字符集合 [ ] 里，. 不是元字符；</p>
<p><strong>匹配结果</strong>  </p>
<p><strong>abc.def<span>@</span>qq.com</strong>  </p>
<ul>
<li><strong>{n}</strong>   匹配 n 个字符</li>
<li><strong>{m,n}</strong>   匹配 m~n 个字符</li>
<li><strong>{m,}</strong>   至少匹配 m 个字符</li>
</ul>
<p>* 和 + 都是贪婪型元字符，会匹配尽可能多的内容。在后面加 ? 可以转换为懒惰型元字符，例如 *?、+? 和 {m,n}? 。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight livecodeserver"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">a</span>.+c</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<p><strong>abcabcabc</strong>  </p>
<p>由于 + 是贪婪型的，因此 .+ 会匹配更可能多的内容，所以会把整个 abcabcabc 文本都匹配，而不是只匹配前面的 abc 文本。用懒惰型可以实现匹配前面的。</p>
<h1 id="六、位置匹配"><a href="#六、位置匹配" class="headerlink" title="六、位置匹配"></a>六、位置匹配</h1><h2 id="单词边界"><a href="#单词边界" class="headerlink" title="单词边界"></a>单词边界</h2><p><strong>\b</strong>   可以匹配一个单词的边界，边界是指位于 \w 和 \W 之间的位置；<strong>\B</strong> 匹配一个不是单词边界的位置。</p>
<p>\b 只匹配位置，不匹配字符，因此 \babc\b 匹配出来的结果为 3 个字符。</p>
<h2 id="字符串边界"><a href="#字符串边界" class="headerlink" title="字符串边界"></a>字符串边界</h2><p><strong>^</strong>   匹配整个字符串的开头，<strong>$</strong> 匹配结尾。</p>
<p>^ 元字符在字符集合中用作求非，在字符集合外用作匹配字符串的开头。</p>
<p>分行匹配模式（multiline）下，换行被当做字符串的边界。</p>
<p><strong>应用</strong>  </p>
<p>匹配代码中以 // 开始的注释行</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight taggerscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">^<span class="symbol">\s</span>*<span class="symbol">\/</span><span class="symbol">\/</span>.*$</span><br></pre></td></tr></table></figure>

<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/600e9c75-5033-4dad-ae2b-930957db638e.png"> </div><br>

<p><strong>匹配结果</strong>  </p>
<ol>
<li>public void fun() {</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;      <strong>// 注释 1</strong>  </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;    int a = 1;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;    int b = 2;</li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;      <strong>// 注释 2</strong>  </li>
<li>&nbsp;&nbsp;&nbsp;&nbsp;    int c = a + b;</li>
<li>}</li>
</ol>
<h1 id="七、使用子表达式"><a href="#七、使用子表达式" class="headerlink" title="七、使用子表达式"></a>七、使用子表达式</h1><p>使用   <strong>( )</strong>   定义一个子表达式。子表达式的内容可以当成一个独立元素，即可以将它看成一个字符，并且使用 * 等元字符。</p>
<p>子表达式可以嵌套，但是嵌套层次过深会变得很难理解。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight clojure"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="name">ab</span>)&#123;<span class="number">2</span>,&#125;</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<p><strong>ababab</strong>  </p>
<p><strong>|</strong>   是或元字符，它把左边和右边所有的部分都看成单独的两个部分，两个部分只要有一个匹配就行。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="number">19</span>|<span class="number">20</span>)\d&#123;<span class="number">2</span>&#125;</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<ol>
<li><strong>1900</strong>  </li>
<li><strong>2010</strong>  </li>
<li>1020</li>
</ol>
<p><strong>应用</strong>  </p>
<p>匹配 IP 地址。</p>
<p>IP 地址中每部分都是 0-255 的数字，用正则表达式匹配时以下情况是合法的：</p>
<ul>
<li>一位数字</li>
<li>不以 0 开头的两位数字</li>
<li>1 开头的三位数</li>
<li>2 开头，第 2 位是 0-4 的三位数</li>
<li>25 开头，第 3 位是 0-5 的三位数</li>
</ul>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">((<span class="number">25</span>[<span class="number">0</span><span class="number">-5</span>]|(<span class="number">2</span>[<span class="number">0</span><span class="number">-4</span>]\d)|(<span class="number">1</span>\d&#123;<span class="number">2</span>&#125;)|([<span class="number">1</span><span class="number">-9</span>]\d)|(\d))\.)&#123;<span class="number">3</span>&#125;(<span class="number">25</span>[<span class="number">0</span><span class="number">-5</span>]|(<span class="number">2</span>[<span class="number">0</span><span class="number">-4</span>]\d)|(<span class="number">1</span>\d&#123;<span class="number">2</span>&#125;)|([<span class="number">1</span><span class="number">-9</span>]\d)|(\d))</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<ol>
<li><strong>192.168.0.1</strong>  </li>
<li>00.00.00.00</li>
<li>555.555.555.555</li>
</ol>
<h1 id="八、回溯引用"><a href="#八、回溯引用" class="headerlink" title="八、回溯引用"></a>八、回溯引用</h1><p>回溯引用使用   <strong>\n</strong>   来引用某个子表达式，其中 n 代表的是子表达式的序号，从 1 开始。它和子表达式匹配的内容一致，比如子表达式匹配到 abc，那么回溯引用部分也需要匹配 abc 。</p>
<p><strong>应用</strong>  </p>
<p>匹配 HTML 中合法的标题元素。</p>
<p><strong>正则表达式</strong>  </p>
<p>\1 将回溯引用子表达式 (h[1-6]) 匹配的内容，也就是说必须和子表达式匹配的内容一致。</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;(h[<span class="number">1</span><span class="number">-6</span>])&gt;\w*?&lt;\/\<span class="number">1</span>&gt;</span><br></pre></td></tr></table></figure>

<p><strong>匹配结果</strong>  </p>
<ol>
<li><strong>&lt;h1&gt;x&lt;/h1&gt;</strong>  </li>
<li><strong>&lt;h2&gt;x&lt;/h2&gt;</strong>  </li>
<li>&lt;h3&gt;x&lt;/h1&gt;</li>
</ol>
<h2 id="替换"><a href="#替换" class="headerlink" title="替换"></a>替换</h2><p>需要用到两个正则表达式。</p>
<p><strong>应用</strong>  </p>
<p>修改电话号码格式。</p>
<p><strong>文本</strong>  </p>
<p>313-555-1234</p>
<p><strong>查找正则表达式</strong>  </p>
<figure class="highlight clojure"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(\d&#123;<span class="number">3</span>&#125;)(<span class="name"><span class="builtin-name">-</span></span>)(\d&#123;<span class="number">3</span>&#125;)(<span class="name"><span class="builtin-name">-</span></span>)(\d&#123;<span class="number">4</span>&#125;)</span><br></pre></td></tr></table></figure>

<p><strong>替换正则表达式</strong>  </p>
<p>在第一个子表达式查找的结果加上 () ，然后加一个空格，在第三个和第五个字表达式查找的结果中间加上 - 进行分隔。</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">($<span class="number">1</span>) $<span class="number">3</span>-$<span class="number">5</span></span><br></pre></td></tr></table></figure>

<p><strong>结果</strong>  </p>
<p>(313) 555-1234</p>
<h2 id="大小写转换"><a href="#大小写转换" class="headerlink" title="大小写转换"></a>大小写转换</h2><table>
<thead>
<tr>
<th align="center">元字符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">\l</td>
<td align="center">把下个字符转换为小写</td>
</tr>
<tr>
<td align="center">\u</td>
<td align="center">把下个字符转换为大写</td>
</tr>
<tr>
<td align="center">\L</td>
<td align="center">把\L 和\E 之间的字符全部转换为小写</td>
</tr>
<tr>
<td align="center">\U</td>
<td align="center">把\U 和\E 之间的字符全部转换为大写</td>
</tr>
<tr>
<td align="center">\E</td>
<td align="center">结束\L 或者\U</td>
</tr>
</tbody></table>
<p><strong>应用</strong>  </p>
<p>把文本的第二个和第三个字符转换为大写。</p>
<p><strong>文本</strong>  </p>
<p>abcd</p>
<p><strong>查找</strong>  </p>
<figure class="highlight clojure"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(\w)(\w&#123;<span class="number">2</span>&#125;)(\w)</span><br></pre></td></tr></table></figure>

<p><strong>替换</strong>  </p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$<span class="number">1</span>\U$<span class="number">2</span>\E$<span class="number">3</span></span><br></pre></td></tr></table></figure>

<p><strong>结果</strong>  </p>
<p>aBCd</p>
<h1 id="九、前后查找"><a href="#九、前后查找" class="headerlink" title="九、前后查找"></a>九、前后查找</h1><p>前后查找规定了匹配的内容首尾应该匹配的内容，但是又不包含首尾匹配的内容。</p>
<p>向前查找使用   <strong>?=</strong>   定义，它规定了尾部匹配的内容，这个匹配的内容在 ?= 之后定义。所谓向前查找，就是规定了一个匹配的内容，然后以这个内容为尾部向前面查找需要匹配的内容。向后匹配用 ?&lt;= 定义（注: JavaScript 不支持向后匹配，Java 对其支持也不完善）。</p>
<p><strong>应用</strong>  </p>
<p>查找出邮件地址 @ 字符前面的部分。</p>
<p><strong>正则表达式</strong>  </p>
<figure class="highlight fix"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">\w+(?</span>=<span class="string">@)</span></span><br></pre></td></tr></table></figure>

<p><strong>结果</strong>  </p>
<p><strong>abc</strong>  @qq.com</p>
<p>对向前和向后查找取非，只要把 = 替换成 ! 即可，比如 (?=) 替换成 (?!) 。取非操作使得匹配那些首尾不符合要求的内容。</p>
<h1 id="十、嵌入条件"><a href="#十、嵌入条件" class="headerlink" title="十、嵌入条件"></a>十、嵌入条件</h1><h2 id="回溯引用条件"><a href="#回溯引用条件" class="headerlink" title="回溯引用条件"></a>回溯引用条件</h2><p>条件为某个子表达式是否匹配，如果匹配则需要继续匹配条件表达式后面的内容。</p>
<p><strong>正则表达式</strong>  </p>
<p>子表达式 (\() 匹配一个左括号，其后的 ? 表示匹配 0 个或者 1 个。 ?(1) 为条件，当子表达式 1 匹配时条件成立，需要执行 ) 匹配，也就是匹配右括号。</p>
<figure class="highlight scheme"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(\()?abc(<span class="name">?</span>(<span class="name">1</span>)\))</span><br></pre></td></tr></table></figure>

<p><strong>结果</strong>  </p>
<ol>
<li><strong>(abc)</strong>  </li>
<li><strong>abc</strong>  </li>
<li>(abc</li>
</ol>
<h2 id="前后查找条件"><a href="#前后查找条件" class="headerlink" title="前后查找条件"></a>前后查找条件</h2><p>条件为定义的首尾是否匹配，如果匹配，则继续执行后面的匹配。注意，首尾不包含在匹配的内容中。</p>
<p><strong>正则表达式</strong>  </p>
<p> ?(?=-) 为前向查找条件，只有在以 - 为前向查找的结尾能匹配 \d{5} ，才继续匹配 -\d{4} 。</p>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">\<span class="name">d</span><span class="string">&#123;5&#125;</span></span>(?(?=-)-<span class="tag">\<span class="name">d</span><span class="string">&#123;4&#125;</span></span>)</span><br></pre></td></tr></table></figure>

<p><strong>结果</strong>  </p>
<ol>
<li><strong>11111</strong>  </li>
<li>22222-</li>
<li><strong>33333-4444</strong>  </li>
</ol>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ul>
<li>BenForta. 正则表达式必知必会 [M]. 人民邮电出版社, 2007.</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>创作不易，欢迎打赏！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Lei Zhou 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Lei Zhou 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>


  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AE%9E%E7%94%A8%E5%B7%A5%E5%85%B7/" rel="tag"><i class="fa fa-tag"></i> 实用工具</a>
          
            <a href="/tags/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="tag"><i class="fa fa-tag"></i> 正则表达式</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/%E8%AE%A1%E7%AE%97%E6%9C%BA%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F%20-%20%E8%AE%BE%E5%A4%87%E7%AE%A1%E7%90%86/" rel="next" title="操作系统原理——设备管理">
                <i class="fa fa-chevron-left"></i> 操作系统原理——设备管理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C-HTTP/" rel="prev" title="计算机网络——http">
                计算机网络——http <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/title.gif"
                alt="Lei Zhou" />
            
              <p class="site-author-name" itemprop="name">Lei Zhou</p>
              <p class="site-description motion-element" itemprop="description">业精于勤，荒于嬉；行成于思，毁于随</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">134</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">69</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zlleige" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/zlleige" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-crosshairs"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.cnblogs.com/zlleige/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i>博客园</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/zlleige" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-paper-plane-o"></i>知乎</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#一、概述"><span class="nav-number">1.</span> <span class="nav-text">一、概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、匹配单个字符"><span class="nav-number">2.</span> <span class="nav-text">二、匹配单个字符</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#三、匹配一组字符"><span class="nav-number">3.</span> <span class="nav-text">三、匹配一组字符</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#四、使用元字符"><span class="nav-number">4.</span> <span class="nav-text">四、使用元字符</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#匹配空白字符"><span class="nav-number">4.1.</span> <span class="nav-text">匹配空白字符</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#匹配特定的字符"><span class="nav-number">4.2.</span> <span class="nav-text">匹配特定的字符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-数字元字符"><span class="nav-number">4.2.1.</span> <span class="nav-text">1. 数字元字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-字母数字元字符"><span class="nav-number">4.2.2.</span> <span class="nav-text">2. 字母数字元字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-空白字符元字符"><span class="nav-number">4.2.3.</span> <span class="nav-text">3. 空白字符元字符</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#五、重复匹配"><span class="nav-number">5.</span> <span class="nav-text">五、重复匹配</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#六、位置匹配"><span class="nav-number">6.</span> <span class="nav-text">六、位置匹配</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#单词边界"><span class="nav-number">6.1.</span> <span class="nav-text">单词边界</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#字符串边界"><span class="nav-number">6.2.</span> <span class="nav-text">字符串边界</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#七、使用子表达式"><span class="nav-number">7.</span> <span class="nav-text">七、使用子表达式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#八、回溯引用"><span class="nav-number">8.</span> <span class="nav-text">八、回溯引用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#替换"><span class="nav-number">8.1.</span> <span class="nav-text">替换</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#大小写转换"><span class="nav-number">8.2.</span> <span class="nav-text">大小写转换</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#九、前后查找"><span class="nav-number">9.</span> <span class="nav-text">九、前后查找</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#十、嵌入条件"><span class="nav-number">10.</span> <span class="nav-text">十、嵌入条件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#回溯引用条件"><span class="nav-number">10.1.</span> <span class="nav-text">回溯引用条件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#前后查找条件"><span class="nav-number">10.2.</span> <span class="nav-text">前后查找条件</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考资料"><span class="nav-number">11.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2019 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zlleige</span>

  
</div>

<!-- 

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>





-->



<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共124.7k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'upVVfHMDcdxMK5SBrji2hCTc-gzGzoHsz',
        appKey: 'zMXMLtk9W57v27fepiRocOrc',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('复制成功')
          else $(this).text('复制失败')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('复制')
        }, 300)
      }).append(e)
    })
  </script>


  
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"model":{"jsonPath":"/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":false},"log":false});</script></body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

